<template>
  <base-load-page :loadState="false" class="base-load-page">
    <template #head>
      <div style="padding-bottom: 15px" class="head-box">
        <div class="left-box">
          <base-date-picker
            v-model="dataRange"
            valueFormat="YYYY-MM-DD"
            format="YYYY-MM-DD"
            type="daterange"
            startPlaceholder="开始日期"
            endPlaceholder="结束日期"
            style="flex-grow: 0; width: 350px"
            clearable
            @change="getAxiosData(true)"
          ></base-date-picker>
          <base-input-search
            v-model="filterData.compileName"
            clearable
            placeholder="请输入编辑名称"
            style="width: 230px"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
          <el-button type="primary" @click="clickExport">数据导出</el-button>
        </div>
        <div class="right-box">
          <el-button type="success" :icon="EpPlus" @click="addHandler">新增</el-button>
        </div>
      </div>
    </template>
    <div class="page-contnet">
      <el-table
        ref="elTableRef"
        v-loading="baseData.loading"
        border
        height="100%"
        :data="tableData"
        showOverflowTooltip
        stripe
        style="width: 100%"
        @sort-change="sortChangeHandel"
      >
        <template #empty>
          <base-empty :description="description" :pageLoadButton="[{ text: '重新加载', callBack: () => getAxiosData() }]"></base-empty>
        </template>
        <el-table-column
          fixed
          type="index"
          :index="(index: number) => (filterData.current - 1) * filterData.size + index + 1"
          label="编号"
          sortable
          width="60"
          align="center"
          headerAlign="center"
        ></el-table-column>
        <el-table-column label="编辑名称" minWidth="160" prop="compileName"></el-table-column>
        <el-table-column label="总消耗" prop="statCost" minWidth="120" sortable="custom">
          <template #header>
            <span>总消耗</span>
            <!-- <span class="highlighted" style="padding-left: 4px; font-weight: bold; text-decoration: none; cursor: default">(xx)</span> -->
          </template>
          <template #default="{ row }">
            <span>{{ formatNumberWithMoney(row.statCost) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="展示数" prop="showCnt" minWidth="120" sortable="custom">
          <template #default="{ row }">
            <span>{{ row.showCnt || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="平均千次展现费用" prop="cpmPlatform" minWidth="170" sortable="custom">
          <template #default="{ row }">
            <span>{{ row.cpmPlatform || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="点击数" prop="clickCnt" minWidth="120" sortable="custom">
          <template #default="{ row }">
            <span>{{ row.clickCnt || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="点击率" prop="ctr" minWidth="120" sortable="custom">
          <template #default="{ row }">
            <span>{{ row.ctr || 0 }}%</span>
          </template>
        </el-table-column>
        <el-table-column label="转化数" prop="convertCnt" minWidth="120" sortable="custom">
          <template #default="{ row }">
            <span>{{ row.convertCnt || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="转化成本" prop="conversionCost" minWidth="120" sortable="custom">
          <template #default="{ row }">
            <span>{{ row.conversionCost || 0 }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 
      <template #foot>
      <div class="pagination-box">
      <el-pagination
      v-model:currentPage="filterData.current"
      v-model:pageSize="filterData.size"
      :pageSizes="[20, 30, 40, 50]"
      :disabled="baseData.loading"
      :pagerCount="13"
      layout="total, prev, pager, next, sizes, jumper"
      :total="baseData.total"
      @change="getAxiosData(true)"
      ></el-pagination>
      </div>
      </template> 
    -->
  </base-load-page>
</template>

<script setup lang="ts">
  import IconSearch from '~icons/ep/search';
  import EpPlus from '~icons/ep/plus';
  import {
    type CompilePeopleRecord,
    type OceMaterialRecordReq,
    addCompilePeopleRecord,
    consumptionRecordExcel,
    getCompilePeopleRecord,
  } from '@/api/marketing-management';
  import { easeDownloadFile } from '@/utils/common.ts';
  import { formatNumberWithMoney } from '@/utils/numb';
  const { proxy } = getCurrentInstance() as any;

  const elTableRef: $RefComp<'ElTable'> = ref(null);
  const baseData = shallowReactive({
    type: 'add' as 'add' | 'edit',
    /** 加载状态 */
    loading: true,
    /** 总数量 */
    total: 0,
  });
  const dataRange = ref<[string, string] | undefined>();
  const filterData = ref<OceMaterialRecordReq>({
    current: 1,
    size: 1000,
    startDate: '',
    endDate: '',
    compileName: '',
    column: '',
    asc: false,
  });

  const tableData: Ref<CompilePeopleRecord[]> = ref([]);
  const description = ref('');

  onMounted(() => {
    // filterData.value.currentDate = proxy.$dayjs().format('YYYY-MM-DD');
    dataRange.value = [proxy.$dayjs().format('YYYY-MM-DD'), proxy.$dayjs().format('YYYY-MM-DD')];
    getAxiosData();
  });

  /** 重置 */
  function initPageData() {
    tableData.value = [];
  }

  /** 数据导出 */
  const clickExport = async () => {
    const res = await consumptionRecordExcel(filterData.value);
    easeDownloadFile(res, '编辑素材消耗');
  };
  /**
   * 设置表格数据
   */
  async function getAxiosData(showLoading = true) {
    if (Array.isArray(dataRange.value) && dataRange.value.length) {
      filterData.value.startDate = dataRange.value[0];
      filterData.value.endDate = dataRange.value[1];
    } else {
      filterData.value.startDate = '';
      filterData.value.endDate = '';
    }
    try {
      await nextTick();
      baseData.loading = Boolean(showLoading);
      const res = await getCompilePeopleRecord(filterData.value);
      if (res.data) {
        tableData.value = res.data as any;
        // filterData.value.current = res.data.current;
        // filterData.value.size = res.data.size;
        // baseData.total = res.data.total;
      } else {
        description.value = '暂无数据';
        initPageData();
      }
      baseData.loading = false;
    } catch (error) {
      baseData.loading = false;
      initPageData();
      description.value = error.msg || '加载失败，-BD001';
    }
  }

  const sortProps = ['statCost', 'showCnt', 'cpmPlatform', 'clickCnt', 'ctr', 'convertCnt', 'conversionCost'];

  /** 表格列排序 */
  const sortChangeHandel = ({ prop, order }: { prop: string; order: 'ascending' | 'descending' | null }) => {
    if (sortProps.includes(prop)) {
      filterData.value.column = prop;
      if (order === 'ascending') {
        filterData.value.asc = true;
      } else if (order === 'descending') {
        filterData.value.asc = false;
      } else {
        filterData.value.column = '';
        filterData.value.asc = false;
      }
      getAxiosData(true);
    } else {
      filterData.value.column = '';
      filterData.value.asc = false;
    }
  };

  /** 新增 */
  const addHandler = () => {
    const compileName = ref<string>('');
    ElMessageBox({
      title: '编辑名称',
      message: () =>
        h(ElInput, {
          modelValue: compileName.value,
          style: 'width:396px',
          placeholder: '请输入编辑名称',
          'onUpdate:modelValue': (val: string) => {
            compileName.value = val.trim();
          },
        }),
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      draggable: true,
      beforeClose: async (a, s, d) => {
        if (a === 'confirm') {
          s.confirmButtonLoading = true;
          if (!compileName.value) {
            ElToast.warning('请输入编辑名称');
          } else {
            await addCompilePeopleRecord({ compileName: compileName.value });
            ElToast.success('操作成功');
            getAxiosData();
            d();
          }
          s.confirmButtonLoading = false;
        } else {
          d();
        }
      },
    }).catch((e) => {
      console.log(e);
    });
  };
</script>

<style lang="scss" scoped>
  .pagination-box {
    @include flex(row, nowrap, center, center, center);
    padding-top: 15px;
  }

  .head-box {
    @include flex(row, nowrap, flex-start, center, center);
    align-items: start;

    .left-box {
      // display: grid;
      display: flex;
      flex: 1;
      flex-wrap: wrap;
      // grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      // grid-gap: 15px;
      gap: 14px;
      margin-right: 15px;
    }
  }

  .page-contnet {
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .content-wrap {
    white-space: wrap;
  }
</style>
